﻿<%@ WebHandler Language="C#" Class="GZContainerBomPrintHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;

//Description: 工装工具分厂[工装毛料成套卡片]打印处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhunan
//create Date:2022-03-09

public class GZContainerBomPrintHandler : IHttpHandler, IRequiresSessionState
{
    GZContainerBusiness gzBusiness = new GZContainerBusiness();
    const int PAGE_MAX_ROW_COUNT = 34; //每页最多显示的行数
    const int HEADER_ROW_COUNT = 5; //头部行数
    const int FOOTER_ROW_COUNT = 8;//底部行数
    int currentRowCount = 0;//当前页已占用的行数 
    int totolPage = 1;//总页数
    int currentPage = 1;//当前页
    int index = 1;//序号
    string html = "";//最终结果
    DataTable dtMain;
    DataTable dtBom;

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetPage":
                    InitPage(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPage(HttpContext context)
    {
        string strHtml = string.Empty;
        List<Dictionary<string, object>> printSession = (List<Dictionary<string, object>>)context.Session["PrintInfo"];
        context.Session.Remove("PrintInfo");
        if (printSession != null && printSession.Count > 0)
        {
            for (int i = 0; i < printSession.Count; i++)
            {
                DataSet resultSet = gzBusiness.GetGZBomPrintInfo(printSession[i]);
                if (resultSet.Tables.Count == 0 || resultSet.Tables["dtMain"].Rows.Count == 0)
                {
                    continue;
                }
                strHtml += GenerateResultHtml(resultSet);
            }
        }
        else
        {
            string ContainerId = context.Request["ContainerId"];
            string WorkflowId = context.Request["WorkflowId"];
            if (string.IsNullOrEmpty(ContainerId) || string.IsNullOrEmpty(WorkflowId))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "刷新无效，请关闭后重新打印", Result = false }));
                return;
            }
            Dictionary<string, object> printInfo = new Dictionary<string, object>();
            printInfo["ContainerId"] = ContainerId;
            printInfo["WorkflowId"] = WorkflowId;
            DataSet resultSet = gzBusiness.GetGZBomPrintInfo(printInfo);

            if (resultSet.Tables.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未找到批次", Result = false }));
                return;
            }
            strHtml += GenerateResultHtml(resultSet);
        }
        //返回值是html
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, ReturnData = strHtml }));
    }
    
    //生成返回的html
    string GenerateResultHtml(DataSet ds)
    {
        dtMain = ds.Tables["dtMain"]; //数据主表
        dtBom = ds.Tables["dtBom"]; //BOM 信息
        
        html = "";
        currentRowCount = 0;//当前页已占用的行数 
        totolPage = 1;//总页数
        currentPage = 1;//当前页
        index = 1;//序列号

        //计算总页数
        if ((dtBom.Rows.Count % 21) <= 21)
        {
            totolPage = (dtBom.Rows.Count / 21) + 1;
        }
        else if ((dtBom.Rows.Count % 21) >= 22 && (dtBom.Rows.Count % 21) <= 28)
        {
            totolPage = (dtBom.Rows.Count / 21) + 2;
        }

        //生成头部
        html += GenerateHeaderHtml(dtMain);

        foreach (DataRow dr in dtBom.Rows)
        {
            if (currentPage < totolPage)//不是最后一页
            {
                if (currentRowCount < PAGE_MAX_ROW_COUNT)
                {
                    html += GenerateMainHtml(dr);
                    currentRowCount++;
                }
                else
                {
                    html += "<div style='width:700px;height:0px;margin-bottom:0px;PAGE-BREAK-BEFORE:always;'></div>";
                    currentPage++;
                    //分页之后立马生成header
                    html += GenerateHeaderHtml(dtMain);
                    //bom没填充完，所以此次循环需要填充数据
                    html += GenerateMainHtml(dr);
                    currentRowCount++;
                }
            }
            else//填充最后一页的剩余内容
            {
                html += GenerateMainHtml(dr);
                currentRowCount++;
            }
        }

        int emptyRowsCount = 0;//补空白行数
        //bom填充完毕
        if (PAGE_MAX_ROW_COUNT >= (FOOTER_ROW_COUNT + currentRowCount))
        {
            //填充空白行
            emptyRowsCount = PAGE_MAX_ROW_COUNT - FOOTER_ROW_COUNT - currentRowCount;
            FillEmptyRows(emptyRowsCount);
            html += GenerateFooterHtml(dtMain);//生成底部
        }
        else
        {
            emptyRowsCount = PAGE_MAX_ROW_COUNT - currentRowCount;
            //剩余空行补充完毕
            FillEmptyRows(emptyRowsCount);
            //分页并增加页头，页脚
            html += "<div style='width:700px;height:0px;margin-bottom:0px;PAGE-BREAK-BEFORE:always;'></div>";
            currentPage++;
            html += GenerateHeaderHtml(dtMain);
            emptyRowsCount = PAGE_MAX_ROW_COUNT - currentRowCount - FOOTER_ROW_COUNT;
            FillEmptyRows(emptyRowsCount);
            html += GenerateFooterHtml(dtMain);//生成底部
        }
        return html;
    }

    //填充空行
    void FillEmptyRows(int rowsCount) 
    {
        for (int i = 0; i < rowsCount; i++)
        {
            html += GenerateMainHtml(dtBom.NewRow());
            currentRowCount++;
        }
    }

    //生成表头html
    string GenerateHeaderHtml(DataTable dtMain)
    {
        string header = "";
        header += "<table style='text-align:left;'>";
        header += "<caption class='title'>工装毛料成套卡片</caption>";
        header += "<tr>";
        header += "<td width='40'>图号：</td>";
        header += string.Format("<td width='150'>{0}</td>",dtMain.Rows[0]["productname"]);
        header += "<td width='55'>任务号：</td>";
        header += string.Format("<td width='250'>{0}</td>", dtMain.Rows[0]["containername"]);
        header += "<td width='40'>套数：</td>";
        header += string.Format("<td width='40'>{0}</td>", dtMain.Rows[0]["qty"]);
        header += string.Format("<td style='text-align:right'>第 {0} 页 共 {1} 页 </td>", currentPage, totolPage);
        header += "</tr>";
        header += "</table>";

        header += "<table class='table'>";
        header += "<tr>";
        header += "  <td rowspan='2' width='30' style='padding: 0 2px;'>序号</td>";
        header += "  <td rowspan='2' width='150'>零件号</td>";
        header += "  <td rowspan='2' width='30' style='padding: 0 2px;'>零件数量</td>";
        header += "  <td colspan='2'>材料</td>";
        header += "  <td rowspan='2' width='30' style='padding: 0 2px;'>毛料数量</td>";
        header += "  <td rowspan='2' width='60'>锻铸件申请号</td>";
        header += "  <td rowspan='2' width='80'>物料码</td>";
        header += "  <td rowspan='2'>重量（公斤）</td>";
        header += "</tr>";
        
        header += "<tr>";
        header += "  <td width='100'>材料牌号</td>";
        header += "  <td width='100'>规格尺寸</td>";
        header += "</tr>";
        header += "</table>";
        currentRowCount = HEADER_ROW_COUNT;
        return header;
    }

    //中间各数据行
    string GenerateMainHtml(DataRow dr)
    {
        //每页最多显示33行 页头占5行 页脚占8行
        string main = "";
        main += "<table class='table'>";
        main += "<tr>";
        main += string.Format("<td width='30' style='padding: 0 2px;'>{0}</td>", dr["subproductname"].ToString() == "" ? "" : index.ToString());//序号
        main += string.Format("<td width='150px'>{0}</td>", dr["subproductname"]);//零件号
        main += string.Format("<td width='30' style='padding: 0 2px;'>{0}</td>", dr["requireqty"]);//零件数量
        main += string.Format("<td width='100'>{0}</td>", dr["materialtrademark"]);//材料牌号
        main += string.Format("<td width='100'>{0}</td>", dr["materialspecification"]);//尺寸规格
        main += string.Format("<td width='30' style='padding: 0 2px;'>{0}</td>", dr["materialsize"]);//毛料数量
        main += string.Format("<td width='60'>{0}</td>", "");//锻铸件申请号
        main += string.Format("<td width='80'>{0}</td>", dr["materialcode"]);//物料码
        main += string.Format("<td>{0}</td>", dr["requireqty2"]);//重量（公斤）
        main += "</tr>";
        main += "</table>";
        index++;
        return main;
    }

    /// <summary>
    /// 生产底部html
    /// </summary>
    /// <returns></returns>
    string GenerateFooterHtml(DataTable dtMain)
    {
        string footer = "";
        footer += "<table class='table'>";
        footer += "<tr>";
        footer += "  <td rowspan='2' width='30' style='padding: 0 2px;'>加工车间</td>";
        footer += "  <td width='320'><div style='text-align:left;padding-left: 5px;'><span>工艺室主任：</span><span></span></div></td>";
        footer += "  <td rowspan='2' width='30' style='padding: 0 2px;'>下料车间</td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>下料人：</span><span></span></div></td>";
        footer += "</tr>";
        footer += "<tr>";
        string gongyiyuan = dtMain.Rows[0]["gongyiyuan"].ToString();
        gongyiyuan = gongyiyuan.Contains("&") ? gongyiyuan.Split('&')[1] + " " + gongyiyuan.Split('&')[0] : "";
        footer += string.Format("  <td><div style='text-align:left;padding-left: 5px;'><span>工艺员：</span><span>{0}</span></div></td>", gongyiyuan);
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>发料人：</span><span></span></div></td>";
        footer += "</tr>";
        footer += "</table>";

        footer += "<table class='table'>";
        footer += "<tr height='60'>";
        footer += "  <td width='30' style='padding: 0 2px;'>车间登账单</td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>图号：</span><span></span></div></td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>任务号：</span><span></span></div></td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>数量：</span><span></span></div></td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>签收：</span><span></span></div></td>";
        footer += "  <td>";
        footer += "     <div style='height: 30px;line-height:30px;text-align:left;padding-left: 5px;'><span>库号：</span><span></span></div>";
        footer += "     <div style='height: 30px;line-height:30px;text-align:left;padding-left: 5px;'></div>";
        footer += "  </td>";
        footer += "</tr>";
        footer += "</table>";

        footer += "<table class='table'>";
        footer += "<tr>";
        footer += "  <td rowspan='2' width='30' style='padding: 0 2px;'>成套毛料签收单</td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>图号：</span><span></span></div></td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>任务号：</span><span></span></div></td>";
        footer += "  <td><div style='text-align:left;padding-left: 5px;'><span>套（件）数：</span><span></span></div></td>";
        footer += "</tr>";
        footer += "<tr>";
        footer += "  <td colspan='3'><div style='text-align:left;padding-left: 5px;'><span> 外购件（名称数量）</span><span></span></div></td>";
        footer += "</tr>";
        footer += "</table>";

        footer += "<table class='table'>";
        footer += "<tr style='height: 30px;'>";
        footer += "  <td><div style='text-align: right;padding-right:20px;'><span>工段签收：</span><span></span></div></td>";
        footer += "  <td><div style='text-align: right;padding-right:20px;'><span>库号：</span><span></span></div></td>";
        footer += "</tr>";
        footer += "<tr>";
        footer += "  <td colspan='2' style='text-align: right;padding-right:20px;'></td>";
        footer += "</tr>";
        footer += "</table>";
        return footer;
    }
}